<template>
    <!-- 其他页面调用年度评价 -->
    <div class="e-form">
        <div class="tabs" v-if="Object.keys(basicFormData).length != 0">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <!-- 基本信息 -->
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="处罚明细"
                    name="punishDetail"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <el-tab-pane
                    label="附件信息"
                    name="accessory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfoCon" class="con">
                        <div class="e-form">
                            <div class="tabs">
                                <div class="tabs-title" id="baseInfo">
                                    基本信息
                                </div>
                                <div style="width: 100%" class="form">
                                    <el-form
                                        :model="basicFormData"
                                        label-width="150px"
                                        ref="basicFormData"
                                    >
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    v-if="
                                                        basicFormData.contractName
                                                    "
                                                    label="合同名称"
                                                >
                                                    {{
                                                        basicFormData.contractName
                                                    }}
                                                </el-form-item>
                                                <el-form-item
                                                    v-else
                                                    label="合同名称"
                                                >
                                                    <el-input
                                                        v-model="
                                                            basicFormData.contractName
                                                        "
                                                    >
                                                        <i
                                                            slot="suffix"
                                                            class="
                                                                el-icon-document-copy
                                                            "
                                                            @click="onContract"
                                                        ></i>
                                                    </el-input>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="合同类型">
                                                    {{
                                                        basicFormData.contractType ==
                                                        '1'
                                                            ? '物资采购'
                                                            : basicFormData.contractType ==
                                                              '2'
                                                            ? '周材租赁'
                                                            : basicFormData.contractType ==
                                                              '3'
                                                            ? '加工合同'
                                                            : basicFormData.contractType ==
                                                              '4'
                                                            ? '设备采购合同'
                                                            : basicFormData.contractType ==
                                                              '5'
                                                            ? '设备租赁合同'
                                                            : basicFormData.contractType ==
                                                              '6'
                                                            ? '服务采购合同'
                                                            : ''
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="统一社会信用代码"
                                                >
                                                    {{
                                                        basicFormData.creditCode
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="供应商名称"
                                                >
                                                    {{
                                                        basicFormData.supplierName
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="供应商类型"
                                                >
                                                    {{
                                                        basicFormData.supplierTypeKey
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="供应商品/资质等级"
                                                >
                                                    {{
                                                        basicFormData.qualificationLevelName
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="历史信用等级"
                                                >
                                                    {{
                                                        basicFormData.historyEvaluate
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="当前评价结论"
                                                >
                                                    {{
                                                        basicFormData.evaluationConclusion
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="评价机构">
                                                    {{
                                                        basicFormData.orgName
                                                    }}</el-form-item
                                                >
                                            </el-col>

                                            <el-col :span="12">
                                                <el-form-item
                                                    label="评价日期："
                                                >
                                                    {{ basicFormData.billDate }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="上级机构"
                                                    >{{
                                                        basicFormData.upOrgName
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="状态">
                                                    {{
                                                        statusLable(
                                                            basicFormData.state
                                                        )
                                                    }}</el-form-item
                                                >
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="终期评价"
                                                    >{{
                                                        basicFormData.superiorOrg
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="备注"
                                                    >{{
                                                        basicFormData.superiorOrg
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                    </el-form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 评价明细 -->
                    <div id="rewardDetailsCon" class="con">
                        <div class="tabs-title" id="rewardDetails">
                            评价明细
                        </div>
                        <div class="e-table">
                            <el-table
                                :data="evaluationItems.creditRatingTemplateDtls"
                                border
                                style="width: 100%"
                                ref="table"
                                class="table"
                                :max-height="$store.state.tableHeight"
                                :cell-class-name="cellClsNm"
                                v-sortTable="{
                                    tableData:
                                        evaluationItems.creditRatingTemplateDtls,
                                    _this: this,
                                    ref: 'table'
                                }"
                                row-key="dtlId"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                            >
                                >
                                <el-table-column
                                    key="selection2"
                                    prop="sortIndex"
                                    label="序号"
                                    width="80"
                                >
                                </el-table-column>
                                <el-table-column
                                    key="content"
                                    prop="content"
                                    label="检查内容"
                                    min-width="300"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="score"
                                    label="规定分值"
                                    width="120"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="checker"
                                    label="检查记录"
                                    min-width="300"
                                >
                                    <template slot-scope="scope">
                                        <el-input
                                            v-if="
                                                scope.row.children == null ||
                                                scope.row.children.length == 0
                                            "
                                            v-model="scope.row.checker"
                                        ></el-input>
                                        <span v-else>{{
                                            scope.row.checker
                                        }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="scoreResult"
                                    label="实得分值"
                                    width="150"
                                >
                                    <template slot-scope="scope">
                                        <el-input
                                            @change="calculation"
                                            v-if="
                                                scope.row.children == null ||
                                                scope.row.children.length == 0
                                            "
                                            type="number"
                                            v-model="scope.row.scoreResult"
                                        ></el-input>
                                        <span v-else>{{
                                            scope.row.scoreResult
                                        }}</span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                        <div>
                            <el-form
                                :model="evaluationItems"
                                label-width="150px"
                            >
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="评价得分：">
                                            {{ evaluationItems.evaluate }}
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="综合评价：">
                                            {{
                                                evaluationItems.complexEvaluate ==
                                                '4'
                                                    ? 'D'
                                                    : evaluationItems.complexEvaluate
                                            }}
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <!-- 附件信息 -->
                    <div id="WarehouseCon" class="con">
                        <div class="tabs-title" id="accessory">附件信息</div>
                        <div class="e-table">
                            <AttachComp
                                :bucketName="bucketName"
                                :relationId="billid"
                            ></AttachComp>
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    </div>
</template>
<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations } from 'vuex'
import {
    showSuccessPop,
    selectDataClient
    // openAppClient
} from '@/utils/common'
import subcontractorChange from '@/api/OutsourcingartyAdmin/subcontractorAdmin/subcontractorChange.js'
import subcontractorRAP from '@/api/OutsourcingartyAdmin/subcontractorAdmin/subcontractorRAP.js'
import { creditTemplate } from '@/api/base/outsourcer'
// 按钮
import AttachComp from '@/components/common/attachIndex'
import call from '@/api/OutsourcingartyAdmin/getAllType.js'
import { setItem } from '@/utils/common'

export default {
    components: {
        // ComExaHistory,
        AttachComp
    },
    data () {
        return {
            bucketName: 'OutsourcingartyAdmin', //模块名
            tabsName: 'baseInfo',
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: ''
            },
            tableData: [],
            value: '',
            textarea: '',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            basicFormData: {
                contractName: '', //合同名称
                outerName: '', //供应商名称
                contractType: '', //合同类型
                creditCode: '', //统一社会信用代码
                outerTypeValue: '', //供应商类型
                businessScopeName: '', //供应商品/资质等级
                creditLevelValue: '', //历史信用等级
                evaluateResult: '', //当前评价结论
                evaluateDate: '', //评价日期
                evaluateQuarter: '', //评价季度
                evaluateOrg: '', //评价机构
                superiorsOrg: '', //上级机构
                state: 0
            },
            typeList: [], //类型列表
            rewardsOrPunishmentList: [], //奖惩类型列表
            id: '',
            orgId: '', //机构id
            orgName: '', //机构名称
            kvKey: '', //外包方名称
            kvValue: '', //外包方值
            // 审核对象
            commit: {
                billId: '', //	单据Id
                billType: 6110, //单据编码
                freeNextUnitIndex: 0, //下一步审核步骤
                freeNextUser: '', //	下一步审核人ID
                isPass: true, //审核是否通过
                isShareInAudit: true, //是否共享审核节点
                opinion: '' //审核意见
            },
            //评价条目
            evaluationItems: {
                checker: '',
                complexEvaluate: '',
                dtlId: '',
                evaluate: '',
                id: '', //关联id
                principal: '',
                scoreResult: '',
                creditRatingTemplateDtls: []
            },
            billid: '', //原单id
            auditState: {}, //按钮状态
            isSend: false,
            supplierId: '', //供应商id
            source: '', //来源
            type: '' //类型
        }
    },
    computed: {
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        // 判断状态
        statusLable () {
            return param => {
                const state = this.$store.state.outsourcer.equipData.state
                const obj = state.find(x => x.value == param)
                if (obj !== undefined) {
                    return obj.label
                }
            }
        },
        localSearchData () {
            // 默认设置搜索标志为false，则不进行搜索回调
            const searchForm = this.basicFormData
            this.setAnnualEvaluation(searchForm)
            return searchForm
        }
    },
    created () {
        this.supplierId = this.$route.query.supplierId //供应商id
        this.billid = this.$route.query.billid //单据id
        this.source = this.$route.query.source //来源
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId
        this.orgName = data.userInfo.orgInfo.orgName
        this.getTypeData() //获取分包商类型
        this.getBasicData() //获取基本数据
        this.getCreditTemplate() //获取年度评价明细
    },
    watch: {
        evaluationItems: {
            handler (newVal) {
                // 对象赋值。如果有bug，单独属性赋值
                setItem('evaluationItems', newVal) //将值存储到客户端
            },
            deep: true,
            immediate: true
        },
        basicFormData: {
            handler (newVal) {
                // 对象赋值。如果有bug，单独属性赋值
                setItem('basicFormData', newVal) //将值存储到客户端
            }
        }
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()
        // 保存所有tabName
        const arr = ['baseInfo', 'punishDetail', 'accessory', 'auditHistory']
        this.tabArr = arr
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }
            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth =
            document.documentElement.clientWidth - this.topHeight
        this.screenHeight =
            document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth
            this.screenHeight = document.documentElement.clientHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
    },
    methods: {
        //获取基本信息数据
        async getBasicData () {
            let data = await subcontractorRAP.annualEvaluationGet({
                billId: this.billid
            })
            this.basicFormData = data
        },
        ...mapMutations(['setSelectedInfo', 'setAnnualEvaluation']),
        //获取分包商类型数据
        getTypeData () {
            call.getCredentialTree({ name: '外包方类型', id: '0' }).then(
                res => {
                    let id = ''
                    // 获取想要的类型id
                    res.map(item => {
                        if (item.kvKey == '分包商') {
                            id = item.kvId
                        }
                    })
                    call.getCredentialTree({ name: '外包方类型', id: id }).then(
                        res => {
                            this.typeList = res
                        }
                    )
                }
            )
            call.getCredential('纳税类别').then(res => {
                this.payTaxesTypeList = res
            })
        },
        // 获取年度评价明细
        async getCreditTemplate () {
            let datas = await subcontractorRAP.getannualEvaluationDetailed({
                billId: this.billid //供应商id
            })
            this.evaluationItems = datas
        },

        // 通过供应商查模板
        async getCreditTemplateInformation (val) {
            let data = val.split(',') //将字符串转为数组
            let datas = await creditTemplate(data) //获取评价列表数据
            // 评价模板
            this.$set(
                this.evaluationItems,
                'creditRatingTemplateDtls',
                datas.checkDetails
            )
        },
        // 合同名称查询
        onContract () {
            // 弹窗选择数据
            selectDataClient({
                SelectServiceToken: '/outer/year/evaluate/sup/get/contract', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: this.supplierId,
                Title: '合同选择'
            }).then(val => {
                this.basicFormData = val[0]
                this.getCreditTemplateInformation(
                    this.basicFormData.supplierTypeValue
                )
            })
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('evaluateCon')) {
                    const lastConHeight =
                        document.getElementById('evaluateCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        ctDelete () {
            this.clientPop('info', this.oneDeleteErr, this.delData)
        },
        //删除
        delData () {
            this.$Ajax
                .httpGet({
                    url: '/outer/evaluate/delete',
                    params: {
                        id: this.id
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    if (res.code == 200) {
                        showSuccessPop('删除成功！')
                        this.isSkip = true
                    }
                    this.$router.push('./dynamicEvaluate')
                })
        },
        // 验证必填
        baseSend () {
            this.$refs.basicFormData.validate(async valid => {
                if (valid) {
                    // 验证附件必填
                    this.isSend = true
                }
            })
        },
        // 基本数据保存
        async baseSave () {
            let data = JSON.parse(JSON.stringify(this.basicFormData))
            return new Promise((resolve, reject) => {
                subcontractorRAP
                    .annualEvaluationUpdate(data)
                    .then(() => {
                        resolve('基础数据保存成功')
                        // 刷新页面
                        this.getBasicData()
                    })
                    .catch(err => {
                        this.setError('baseInfo')
                        reject('基础数据保存失败', err)
                    })
            })
        },
        //评价保存
        async rewardsAndPunishmentsSave () {
            // 评价明细保存
            let newRewardData = JSON.parse(
                JSON.stringify(this.evaluationItems)
            )
            newRewardData.id = this.billid
            newRewardData.creditRatingTemplateDtls.map(item => {
                if (item.children) {
                    item.children.map(newItem => {
                        newItem.id = this.billid
                    })
                }
                item.id = this.billid
            })
            return new Promise((resolve, reject) => {
                // 评价保存
                subcontractorRAP
                    .AddannualEvaluationDetailed(newRewardData)
                    .then(() => {
                        resolve('评价保存成功')
                    })
                    .catch(err => {
                        this.setError('baseInfo')
                        reject('评价保存失败', err)
                    })
            })
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        // 点击标签的方法
        onChangeTab (e) {
            const height = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //日期转换格式
        getTime (dt) {
            var year = dt.getFullYear() //年
            var month = dt.getMonth() + 1 //月
            var date = dt.getDate() //日
            month = month < 10 ? '0' + month : month
            date = date < 10 ? '0' + date : date
            var str = year + '-' + month + '-' + date
            return str
        },
        // 计算父级的实际分值
        calculation () {
            let nums = 0
            this.evaluationItems.creditRatingTemplateDtls.map(item => {
                // 初始化子集分数
                let num = 0
                if (item.children) {
                    item.children.map(childrenitem => {
                        if (childrenitem.scoreResult <= childrenitem.score) {
                            if (
                                childrenitem.scoreResult != null &&
                                childrenitem.scoreResult != '' &&
                                childrenitem.scoreResult != undefined
                            ) {
                                num += parseInt(childrenitem.scoreResult)
                            }
                        } else {
                            this.clientPop(
                                'err',
                                '实得分数大于规定分数,请重新输入'
                            )
                            return (childrenitem.scoreResult = 0)
                        }
                    })
                    this.$set(item, 'scoreResult', num)
                }
                if (item.scoreResult <= item.score) {
                    if (!isNaN(parseInt(item.scoreResult))) {
                        nums += parseInt(item.scoreResult)
                    }
                } else {
                    this.clientPop('err', '实得分数大于规定分数,请重新输入')
                    return (item.scoreResult = 0)
                }
            })
            this.evaluationItems.evaluate = nums
            //综合评价，小于60分为D，大于60分显示分数
            if (nums < 60) {
                this.evaluationItems.complexEvaluate = '4'
            } else {
                this.evaluationItems.complexEvaluate = nums
            }
        },
        // 审核历史列表查询
        async getAuditHistory () {
            let data = await subcontractorChange.findByIdAuditHistory({
                billId: this.billid,
                billType: 6110,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            })
            this.tableData = data
        },
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        }
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
    width: 6px; // 横向滚动条
    height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 5px;
}

.el-tab-pane {
    margin-left: -10px;
}
</style>
